﻿#include "widget.h"
#include "ui_widget.h"

// 日出日落底线
const QPoint Widget::sun[2] = {
    QPoint(20, 75),
    QPoint(130, 75)
};
// 日出日落时间
const QRect Widget::sunRizeSet[2] = {
    QRect(0, 80, 50, 20),
    QRect(100, 80, 50, 20)
};

// 日出日落圆弧
const QRect Widget::rect[2] = {
    QRect(25, 25, 100, 100), // 虚线圆弧
    QRect(50, 80, 50, 20) // “日出日落”文本
};

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置无标题、无边框
    //setWindowFlag(Qt::FramelessWindowHint);
    //设置固定大小
    setFixedSize(width(),height());
    this->setWindowTitle(u8"天气预报");
    //初始化界面
    forecast_week_list << ui->week_01 << ui->week_02 << ui->week_03 << ui->week_04 << ui->week_05 << ui->week_06;
    forecast_date_list << ui->date_01 << ui->date_02 << ui->date_03 << ui->date_04 << ui->date_05 << ui->date_06;
    forecast_aqi_list << ui->qutity_1 << ui->qutity_2 << ui->qutity_3 << ui->qutity_4 << ui->qutity_5 << ui->qutity_6;
    forecast_type_list << ui->WeaStatus_1 << ui->WeaStatus_2 << ui->WeaStatus_3 << ui->WeaStatus_4 << ui->WeaStatus_5 << ui->WeaStatus_6;
    forecast_typeIco_list << ui->WeaStatusIcon_1 << ui->WeaStatusIcon_2 << ui->WeaStatusIcon_3 << ui->WeaStatusIcon_4 << ui->WeaStatusIcon_5 << ui->WeaStatusIcon_6;
    forecast_high_list << ui->upperTem_1 << ui->upperTem_2 << ui->upperTem_3 << ui->upperTem_4 << ui->upperTem_5 << ui->upperTem_6;
    forecast_low_list << ui->lowerTem_1 << ui->lowerTem_2 << ui->lowerTem_3 << ui->lowerTem_4 << ui->lowerTem_5 << ui->lowerTem_6;
    // dateLb和WeekLb样式表设置
    for (int i = 0; i < 6; i++)
    {
        forecast_date_list[i]->setStyleSheet("background-color: rgba(0, 255, 255, 100);");
        forecast_week_list[i]->setStyleSheet("background-color: rgba(0, 255, 255, 100);");
    }
    //网络请求初始化
    // 请求天气API信息
    url = "http://t.weather.itboy.net/api/weather/city/";
    city =  u8"西安";
    cityTmp = city;
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replayFinished(QNetworkReply*)));
    getWeatherInfo(manager);
    ui->curveLb->installEventFilter(this);
    //QMessageBox::information(this,"11",QString::number(wt.cityMapCode.size(),10));

}

Widget::~Widget()
{
    delete ui;
}
void Widget::getWeatherInfo(QNetworkAccessManager* manager){
    QString citycode = wt[city];  //获取城市编码
    if(citycode=="000000000"){
        QMessageBox::warning(this, u8"错误", u8"天气：指定城市不存在！", QMessageBox::Ok);
        return;
    }
    //get请求
    QUrl jsonUrl(url + citycode);
    manager->get(QNetworkRequest(jsonUrl)); //触发信号
}
void Widget::replayFinished(QNetworkReply* reply){
    /* 获取响应的信息，状态码为200表示正常 */
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(reply->error() != QNetworkReply::NoError || status_code != 200)
    {
        QMessageBox::warning(this, u8"错误", u8"天气：请求数据错误，检查网络连接！", QMessageBox::Ok);
        return;
    }

    QByteArray bytes = reply->readAll();
    parseJson(bytes);
    setLabelValue();
    //3.温度曲线重新绘制
    ui->curveLb->update();

}
void Widget::parseJson(QByteArray& qa){
    QJsonParseError err;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(qa, &err); // 检测json格式
    if (err.error != QJsonParseError::NoError) // Json格式错误
    {
        return;
    }
    QJsonObject jsObj = jsonDoc.object();
    QString message = jsObj.value("message").toString();
    if (message.contains("success") == false)
    {
        QMessageBox::information(this, tr("The information of Json_desc"),u8"天气：城市错误！", QMessageBox::Ok );
        city = cityTmp;
        return;
    }
    today = jsObj;
    // 解析data中的yesterday
    forecast[0] = jsObj.value("data").toObject().value("yesterday").toObject();

    // 解析data中的forecast  包括今天  明天   后天   大后天 ....
    QJsonArray forecastArr = jsObj.value("data").toObject().value("forecast").toArray();
    int j = 0;
    for (int i = 1; i < 6; i++)
    {
        forecast[i] = forecastArr.at(j).toObject();
        j++;
    }
 }
void Widget::setLabelValue(){
//    // 更新今日数据
    ui->TodayDate->setText(today.date);
    ui->HumidityValue->setText(today.shidu);
    ui->TemperatureValue->setText(today.wendu);
    ui->CityValue->setText(today.city);
    ui->qutity->setText(today.quality);
    ui->WeatherNote->setText(today.notice);
//    ui->shiduLb->setText(today.shidu);
    ui->PMValue->setText(today.pm25);
    ui->WindDirectionValue->setText(today.fx);
    ui->WindPowerValue->setText(today.fl);
    ui->GanMaoValue->setText(today.ganmao);
    // 更新六天数据
    // 六天数据
    for (int i = 0; i < 6; i++)
    {
        forecast_week_list[i]->setText(forecast[i].week);   //.right(3)  设置星期几
        forecast_date_list[i]->setText(forecast[i].date.left(3)); //     设置日期
        forecast_type_list[i]->setText(forecast[i].type);         //     设置天气状态
        forecast_high_list[i]->setText(forecast[i].high.split(" ").at(1));//设置高温  取温度
        forecast_low_list[i]->setText(forecast[i].low.split(" ").at(1));  //设置低温  取温度
        forecast_typeIco_list[i]->setStyleSheet( tr("image: url(:/day/day/%1.png);").arg(forecast[i].type) );// 设置图标

        if (forecast[i].aqi.toInt() >= 0 && forecast[i].aqi.toInt() <= 50)
        {
            forecast_aqi_list[i]->setText(u8"优质");
            forecast_aqi_list[i]->setStyleSheet("color: rgb(0, 255, 0);");
        }
        else if (forecast[i].aqi.toInt() > 50 && forecast[i].aqi.toInt() <= 100)
        {
            forecast_aqi_list[i]->setText(u8"良好");
            forecast_aqi_list[i]->setStyleSheet("color: rgb(255, 255, 0);");
        }
        else if (forecast[i].aqi.toInt() > 100 && forecast[i].aqi.toInt() <= 150)
        {
            forecast_aqi_list[i]->setText(u8"轻度污染");
            forecast_aqi_list[i]->setStyleSheet("color: rgb(255, 170, 0);");
        }
        else if (forecast[i].aqi.toInt() > 150 && forecast[i].aqi.toInt() <= 200)
        {
            forecast_aqi_list[i]->setText(u8"重度污染");
            forecast_aqi_list[i]->setStyleSheet("color: rgb(255, 0, 0);");
        }
        else
        {
            forecast_aqi_list[i]->setText(u8"严重污染");
            forecast_aqi_list[i]->setStyleSheet("color: rgb(170, 0, 0);");
        }
        ui->week_01->setText( u8"昨天" );
        ui->week_02->setText( u8"今天" );
    }


}
//绘制日出日落曲线
void Widget::paintSunRiseSet(){
//    QPainter painter(ui->SunRiseSet);
//    painter.setRenderHint(QPainter::Antialiasing,true);//反抗锯齿设置
//    painter.save();
//    QPen pen = painter.pen();
//    pen.setWidthF(0.5);
//    pen.setColor(Qt::yellow);
//    painter.setPen(pen);
//    painter.drawLine(sun[0], sun[1]);//日落线
//    painter.restore();
//    painter.save();
//    painter.setFont( QFont("Microsoft Yahei", 8, QFont::Normal) ); // 字体、大小、正常粗细
//    painter.setPen(Qt::white);

//    if (today.sunrise != "" && today.sunset != "")
//    {
//        //在指定区域内绘制文字
//        painter.drawText(sunRizeSet[0], Qt::AlignHCenter, today.sunrise);
//        painter.drawText(sunRizeSet[1], Qt::AlignHCenter, today.sunset);
//    }
//    painter.drawText(rect[1], Qt::AlignHCenter, u8"日出日落");//在指定区域绘制文字
//    painter.restore();


//    // 绘制圆弧
//    painter.save();
//    pen.setWidthF(0.5);         //设置线条的宽度0.5
//    pen.setStyle(Qt::DotLine);  //虚线
//    pen.setColor(Qt::green);    //设置颜色
//    painter.setPen(pen);
//    painter.drawArc(rect[0], 0 * 16, 180 * 16); //绘制圆弧
//    painter.restore();



}
void Widget::paintCurve(){
    QPainter painter(ui->curveLb);
    painter.setRenderHint(QPainter::Antialiasing,true);//反抗锯齿设置

    //1.获取数据
    int low[6],high[6],averTem = 0; //记录六天最高温度、最低温度、平均温度
    for(int i = 0;i<6;i++){
        QString h = forecast[i].high.split(" ").at(1);
        h = h.left(h.size()-1);
        high[i] = (int)h.toDouble();

        QString l = forecast[i].low.split(" ").at(1);
        l = l.left(l.size()-1);
        low[i] = (int)l.toDouble();

        averTem +=  high[i];
    }
    averTem = (int)averTem/6;

    //2.开始绘制
       //算出温度对应坐标
    int pointX[6]={41,127,213,299,385,471};
    int pointLY[6]={0};
    int pointHY[6]={0};
    for(int i = 0;i<6;i++){
        pointHY[i] = TEMPERATURE_STARTING_COORDINATE - ((high[i] - averTem) * SPAN_INDEX)-20;
        pointLY[i] = TEMPERATURE_STARTING_COORDINATE + ((averTem - low[i]) * SPAN_INDEX)-20;

    }
    QPen pen = painter.pen();
    pen.setWidth(1);
    // 高温曲线绘制
    painter.save();
    pen.setColor(QColor(255, 170, 0));	//设置颜色
    pen.setStyle(Qt::DotLine);	//虚线
    painter.setPen(pen);//设置画笔
    painter.setBrush(QColor(255, 170, 0));//设置画刷颜色
    painter.drawEllipse(QPoint(pointX[0], pointHY[0]), ORIGIN_SIZE, ORIGIN_SIZE);
    painter.drawEllipse(QPoint(pointX[1], pointHY[1]), ORIGIN_SIZE, ORIGIN_SIZE); //先画两个点
    painter.drawLine(pointX[0], pointHY[0], pointX[1], pointHY[1]);//连接这两个点
    pen.setStyle(Qt::SolidLine);
    pen.setWidth(1);
    painter.setPen(pen);
    for (int i = 1; i < 5; i++)
    {
        painter.drawEllipse(QPoint(pointX[i+1], pointHY[i+1]), ORIGIN_SIZE, ORIGIN_SIZE);
        painter.drawLine(pointX[i], pointHY[i], pointX[i+1], pointHY[i+1]);
    }
    painter.restore();
    // 低温曲线绘制
    pen.setColor(QColor(0, 255, 255));
    pen.setStyle(Qt::DotLine);
    painter.setPen(pen);
    painter.setBrush(QColor(0, 255, 255));
    painter.drawEllipse(QPoint(pointX[0], pointLY[0]), ORIGIN_SIZE, ORIGIN_SIZE);
    painter.drawEllipse(QPoint(pointX[1], pointLY[1]), ORIGIN_SIZE, ORIGIN_SIZE);
    painter.drawLine(pointX[0], pointLY[0], pointX[1], pointLY[1]);

    pen.setColor(QColor(0, 255, 255));
    pen.setStyle(Qt::SolidLine);
    painter.setPen(pen);
    for (int i = 1; i < 5; i++)
    {
        painter.drawEllipse(QPoint(pointX[i+1], pointLY[i+1]), ORIGIN_SIZE, ORIGIN_SIZE);
        painter.drawLine(pointX[i], pointLY[i], pointX[i+1], pointLY[i+1]);
    }



}
void Widget::mousePressEvent(QMouseEvent *event){
    //1.即将移动的距离 = 当前窗口位置 - 当前鼠标位置
    rPosition = event->globalPos() - this->pos();
}
void Widget::mouseMoveEvent(QMouseEvent *event){
    move(event->globalPos() - rPosition);
}
void Widget::keyReleaseEvent(QKeyEvent *event){
    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
    {
        //1.获取城市
        city = ui->CityLine->text();
        //2.获取该城市的信息
        getWeatherInfo(manager);
        //3.清空搜索框内容
        ui->CityLine->setText("");
    }
}
bool Widget::eventFilter(QObject *watched, QEvent *event){
    if (watched == ui->curveLb && event->type() == QEvent::Paint)
    {
        paintCurve();
    }
    return QWidget::eventFilter(watched,event);

}
void Widget::on_SearchButton_clicked()
{
    //1.获取城市
    city = ui->CityLine->text();
    //2.获取该城市的信息
    getWeatherInfo(manager);
    ui->CityLine->setText("");
}
void Widget::on_toolButton_clicked()
{
    //1.刷新
    getWeatherInfo(manager);
}
